<template>
  <div class="notice-list">
    <el-table
      :data="notices"
      style="width: 100%; margin-top: 20px;"
      @row-click="viewNotice"
    >
      <el-table-column prop="noticeTitle" label="公告标题" width="180" />
      <el-table-column label="公告内容">
        <template #default="scope">
          <el-tooltip effect="dark" :content="scope.row.noticeContent" placement="top">
            <div class="notice-content">
              {{ scope.row.noticeContent }}
            </div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="发布时间">
        <!-- 使用格式化方法显示时间 -->
        <template #default="scope">
          {{ formatTime(scope.row.createTime) }}
        </template>
      </el-table-column>
    </el-table>

    <!-- 公告内容弹窗 -->
    <el-dialog title="公告内容" v-model="fullContentVisible" width="40%">
      <div v-html="fullContent"></div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import http from '../utils/axios';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';

const router = useRouter();
const notices = ref([]);

const fullContentVisible = ref(false);
const fullContent = ref('');

// 时间格式化方法
const formatTime = (time) => {
  const date = new Date(time);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}`;
};

// 获取公告列表并排序
const fetchNotices = async () => {
  try {
    const response = await http.get('/notice/all');
    // 按 createTime 排序（从早到晚）
    notices.value = response.data.sort((b, a) => new Date(a.createTime) - new Date(b.createTime));
  } catch (error) {
    ElMessage.error('获取公告列表时发生异常');
  }
};

const viewNotice = (row) => {
  router.push(`/notices/${row.noticeId}`);
};

onMounted(() => {
  fetchNotices();
});
</script>

<style scoped>
.notice-list {
  padding: 20px;
}

.notice-content {
  white-space: pre-wrap; /* 保留空白符序列 */
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  line-clamp: 1;
  -webkit-box-orient: vertical;
  cursor: pointer;
}
</style>
